﻿//基础类库
(function(){

//创建基本对象
if (window.Ctn){
	var _Ctn = window.Ctn;
}
var Ctn = window.Ctn = function(selector, context) {
	return new Ctn.core.Core(selector, context);
};

//通用模块
Ctn.util = {
    //遍历操作
    each:function(object, callback, args){
        if (args) {
		    if (object.length == undefined) {
			    for (var name in object)
				    if (callback.apply(object[ name ], args) === false)
					    break;
		    } else
			    for (var i = 0, length = object.length; i < length; i++)
				    if (callback.apply(object[ i ], args) === false)
					    break;
	    } else {
		    if (object.length == undefined) {
			    for (var name in object)
				    if (callback.call(object[ name ], name, object[ name ]) === false)
					    break;
		    } else
			    for (var i = 0, length = object.length, value = object[0]; 
				    i < length && callback.call(value, i, value) !== false; value = object[++i]){}
	    }

	    return object;
    },
    //功能扩展
    extend:function(dest, source, opt){
        if (opt == null || opt == true){
            for (var k in source) {
                dest[k] = source[k];
            }
        }else if (typeof(opt) == "boolean"){
            for (var k in source) {
                if (!(k in dest[k])){
                    dest[k] = source[k];
                }
            }
        }else if(opt instanceof(Array)){
            opt.each(function(k){dest[k] = source[k]});
        }else if(typeof(opt) == "string"){
            var arr = opt.split(',');
            arr.each(function(k){dest[k] = source[k]});
        }
        return dest;
    },
    //遍历尝试
    tryeach:function(){
        var ret;
        for (var i = 0, l = arguments.length; i < l; i++) {
          var fn = arguments[i];
          try {
            ret = fn();
            break;
          } catch (e) {}
        }
        return ret;
    },
    //克隆对象
    clone:function(obj, deep){
        var o = {};
        for (var k in obj){
            o[k] = (deep && typeof(obj[k]) == 'object') ? this.clone(obj[k]) : obj[k];
        }
        return o;
    },
    //空函数
    emptyFn:function(){}
}
//创建类对象
var Class = {
    //创建对象
    create: function() {
        return function() {
            //调用构造函数
            this._construct.apply(this, arguments);
            //添加监听
            this.addListener = function(fn, cb, args, obj){};
            //移除监听
            this.removeListener = function(fn, cb){};
        }
    }
}

//核心模块
Ctn.core = {
    Core: Class.create(),
    CSS:{
    },
    DOM:{
    }
}
//核心对象
Ctn.core.Core.prototype = {
    _construct: function(selector, context){
    }
}
//xml模块
Ctn.xml = {
}
//XML文档对象
var XMLDoc = Class.create();
XMLDoc.prototype = {
    xmlDoc: null,
    _construct: function(doc){
        if (doc){
            this.xmlDoc = doc;
        }else{
            this.xmlDoc = Ctn.util.tryeach(
                function(){return document.implementation.createDocument('','',null);},
                function(){return new ActiveXObject("Msxml2.DOMDocument.4.0");},
                function(){return new ActiveXObject("Microsoft.XMLDOM");}
            );
            this.xmlDoc.async = false;
        }
    },
    loadXML: function(xmlString){
        var xmldoc = this.xmlDoc;
        if (Ctn.Browser.ie()){
            xmldoc.loadXML(xmlString);
        }else{
            var childNodes = xmldoc.childNodes;
            for (var i = childNodes.length - 1; i >= 0; i--){
                xmldoc.removeChild(childNodes[i]);
            };
            var dp = new DOMParser();
            var newDOM = dp.parseFromString(xmlString, "text/xml");
            var newElt = xmldoc.importNode(newDOM.documentElement, true);
            xmldoc.appendChild(newElt);
        }
    },
    selectNodes: function(xPath, xNode){
        var aResult = [];
        xPath = xPath.replace("//","/");
        xNode = xPath.startsWith("/") ? this.xmlDoc : xNode;
        xPath = xPath.trim("/");
        xNode = xNode ? xNode : this.xmlDoc;
        if (Ctn.Browser.ie()){
            var ns = xNode.selectNodes(xPath);
            for (var i = 0, l = ns.length; i < l; i++){
                aResult.push(new XMLElem(ns[i]));
            }
        }else{
            selectNodes(xNode, xPath, aResult);
        }
        return aResult;
    },
    selectSingleNode: function(xPath, xNode){
        var ret = null;
        xPath = xPath.replace("//","/");
        xNode = xPath.startsWith("/") ? this.xmlDoc : xNode;
        xNode = xNode ? xNode : this.xmlDoc;
        xPath = xPath.trim("/");
        if (Ctn.Browser.ie()){
            var n = xNode.selectSingleNode(xPath);
            if (n != null){
                ret = new XMLElem(n);
            }
        }else{
            ret = selectSingleNode(xNode, xPath);
        }
        return ret;
    },
    xml: function(){
        return this.xmlDoc.xml == undefined ? new XMLSerializer().serializeToString(this.xmlDoc) : this.xmlDoc.xml; 
    },
    val: function(v){
        return this.documentElement().xml(v);
    },
    text: function(v){
        return this.documentElement().text(v);
    },
    attr: function(n, v){
        return this.documentElement().attr(n, v);
    },
    documentElement: function(){
        return new XMLElem(this.xmlDoc.documentElement);
    },
    validate: function(){
    }
}
//XML元素对象
var XMLElem = Class.create();
XMLElem.prototype = {
    xmlElem:null,
    _construct: function(elem){
        this.xmlElem = elem;
    },
    selectNodes:function(xPath){
        return this.ownerDocument().selectNodes(xPath, this.xmlElem);
    },
    selectSingleNode:function(xPath){
        return this.ownerDocument().selectSingleNode(xPath, this.xmlElem);
    },
    xml:function(){
        return this.xmlElem.xml == undefined ? new XMLSerializer().serializeToString(this.xmlElem) : this.xmlElem.xml; 
    },
    val:function(){
        var v = this.xml();
        return v.substring(v.indexOf(">") + 1, v.lastIndexOf("<"));
    },
    text:function(){
        return this.xmlElem.text == undefined ? this.xmlElem.textContent : this.xmlElem.text;
    },
    attr:function(att){
        return this.xmlElem.getAttribute(att);
    },
    ownerDocument:function(){
        return new XMLDoc(this.ownerDocument);
    },
    documentElement:function(){
        return new XMLElem(this.xmlDoc.documentElement);
    },
    childNodes:function(){
        var ns = [];
        var cs = this.xmlDoc.childNodes;
        for (var i = 0, l = cs.length; i < l; i++){
            ns.push(new XMLElem(cs[i]));
        }
        return ns;
    }
}

//扩展普通属性
new Array("nodeType", "nodeValue", "nodeName", "tagName").each(function(n){
    XMLElem.prototype[n] = function(v){
        return this.xmlElem[n];
    }
});
//扩展节点值属性
new Array("parentNode", "firstChild", "lastChild", "nextSibling", "previousSibling").each(function(n){
    XMLDoc.prototype[n] = function(){
        return this.documentElement()[n]();
    }
    XMLElem.prototype[n] = function(){
        return new XMLElem(this.xmlElem[n]);
    }
});
//扩展方法
new Array("load").each(function(n){
    XMLDoc.prototype[n] = function(){
        var a = [];
        for (var i = 0, l = arguments.length; i < l; i++){
            a.push("arguments[" + i + "]");
        }
        return eval("this.xmlDoc[n](" + a.join(",") + ")");
    }
});
//Ajax对象
var Ajax = Class.create();
Ajax.prototype = {
    req: null,
    options:{
        url:'?',
        method:       'post',
        async: true,
        contentType:  'application/x-www-form-urlencoded',
        encoding:     'UTF-8',
        params:   '',
        text: '正在加载中...',
        obj:window,
        args: null,
        loading: true,
        type: 'xml',
        onError: Ctn.util.emptyFn,
        onSuccess: Ctn.util.emptyFn,
        onComplete: Ctn.util.emptyFn,
        onStateChange: Ctn.util.emptyFn
    },
    _construct : function (option){
        this.req = Ctn.util.tryeach(
        function() {return new XMLHttpRequest()},
        function() {return new ActiveXObject('Msxml2.XMLHTTP')},
        function() {return new ActiveXObject('Microsoft.XMLHTTP')}
        );
    },
    request: function(opt){
        var o = this.options;
        Ctn.util.extend(o, opt);
        this.req.onreadystatechange = this.onStateChange.call(this);
        this.req.setRequestHeader("Content-Type", o.contentType + "; charset=" + o.encoding);
        this.req.open(o.url, o.method, o.async);
        this.req.send(o.params);
    },
    onSuccess: function(){
        var o = this.options;
        switch (o.type){
            case "xml": {
            }break;
            default: {
                o.onSuccess(this.req.responseText, o.args);
            }break;
        }
    },
    onError: function(){
    },
    onComplete:function(){
    },
    onStateChange: function(){
        var rs = this.req.readyState;
        if (rs == 4){
            var s = this.req.status;
            if(s == 200 || s == 0){
                this.onSuccess();
            }else{
                this.onError();
            }
        }
    }
}
var userAgent = navigator.userAgent.toLowerCase();
window.Ctn = {
        //版本
    version:2.0,
    Class:{
        create: function() {
            return function() {
                //调用构造函数
                this._construct.apply(this, arguments);
                this.addListener = function(fn, cb, args, obj){};
                this.removeListener = function(fn, cb){};
            }
        }
    },
    Object:{
    },
    //对String的扩展
    String:{
        
    },
    Nunber:{
        NAN0:function(){
            //if (isNaN(this))
        }
    },
    Date:{
    },
    Array:{
        
    },
    Function:{
        bind:function(){}
    },
    Boolean: {
        
    },
    Math:{},
    Error:{
    },
    Event:{
        KEY_BACKSPACE: 8,
        KEY_TAB:       9,
        KEY_RETURN:   13,
        KEY_ESC:      27,
        KEY_LEFT:     37,
        KEY_UP:       38,
        KEY_RIGHT:    39,
        KEY_DOWN:     40,
        KEY_DELETE:   46,
        KEY_HOME:     36,
        KEY_END:      35,
        KEY_PAGEUP:   33,
        KEY_PAGEDOWN: 34,
        objectEvent:[],
        bindElem:function(elem, evt, fn, ts){
        },
        unbindElem:function(elem, evt, fn){
        },
        bindObject:function(obj, evt, fn, ts){
        },
        unbindObject:function(obj, evt, fn){
        },
        exec:function(obj){
        }
    },
    Effect:{
    },
    Browser:{
        //客户端信息
	    msie: /msie/.test(userAgent),
	    firefox: /firefox/.test(userAgent),
        safari: /safari/.test(userAgent),
	    opera: /opera/.test(userAgent),
        version: (userAgent.match(/.+(?:ie|ox|on|ra)[\/: ]([\d.]+)/) || [])[1],
        //msie
        ie:function(v){
            return this.msie && this.ver(v);
        },
        //firefox
        ff:function(v){
            return this.firefox && this.ver(v);
        },
        //safari
        sf:function(v){
            return this.safari && this.ver(v);
        },
        //opera
        op:function(v){
            return this.opera && this.ver(v);
        },
        //比较版本号
        ver:function(v){
            //不写版本号
            if (!v) {
                return true;
            }
            v = v.toString();
            var a,b,c,l,f;
            a = v.substring(v.length - 1);
            if (a == "+" || a == "-"){
                b = this.version.split(".");
                v = v.substring(0, v.length - 1);
                c = v.split(".");
                l = b.length > c.length ?c.length:b.length;
                f = a == "+"?true:false;
                for (var i = 0; i < l; i++){
                    if ((f && c[i] > b[i]) || (!f && c[i] < b[i])){
                        return false;
                    }
                }
                return true;
            }else{
                return this.version.indexOf(ver) == 0;
            }
        }
    },
    XML:{
        XMLDocument:{
            ssn:function(){},
            sns:function(){},
            getDoc:function(){},
            getDoc:function(){},
            validate:function(){}
        },
        XMLElement:{
            ssn:function(){},
            sns:function(){},
            val:function(){},
            text:function(){},
            attr:function(){}
        },
        getXmlDoc:function(){
            var XmlDoc = null ;
            try
            {
                XmlDoc = new ActiveXObject("Msxml2.DOMDocument.4.0") ;
            }
            catch(e)
            {
                try
                {
                    XmlDoc = new ActiveXObject("Microsoft.XMLDOM") ;
                }
                catch(o)
                {
                    if(document.implementation 
                        && document.implementation.createDocument
                        && document.implementation.hasFeature("XPath", "3.0"))
                    {
                        XmlDoc = document.implementation.createDocument('','',null);
                    }
                }
            }
            return XmlDoc;
        }
    },
    DOM:{
    },
    CSS:{
        css:function(){
        },
        height:function(){
        },
        width:function(){
        },
        left:function(){
        },
        top:function(){
        }
    },
    Cache:{
        idx:0,
        data:{},
        add:function(v){
            this.data[this.idx] = v;
            return this.idx++;
        },
        set:function(k, v){
            this.data[k] = v;
        },
        remove:function(k){
            this.data[k] = null;
        },
        clear:function(){
            var d = this.data;
            for (var k in d){
                d[k] = null;
            }
        },
        get:function(k){
            return this.data[k];
        }
    },
    GC:{
        data:[],
        add:function(elem, attr){
            this.data.push([elem,attr]);
        },
        collect:function(){
            var d = this.data;
            for (var i = d.length - 1; i >= 0; i--){
                d[i][0][d[i][1]] = null;
            }
            d.clear();
        }
    },
    Cookie:{
        set:function(name,value,expires,path,domain,secure){
            var expDays = expires*24*60*60*1000;
            var expDate = new Date();
            expDate.setTime(expDate.getTime() + expDays);
            var expString = expires ? "; expires="+expDate.toGMTString() : "";
            var pathString = "; path="+(path||"/");
            var domain = domain ? "; domain="+domain : "";
            document.cookie = name + "=" + escape(value) + expString + domain + pathString + (secure?"; secure":"");
        },
        get:function(k){
            var dc = "; "+document.cookie+"; ";
            var coo = dc.indexOf("; "+k+"=");
            if (coo!=-1){
                var s = dc.substring(coo+k.length+3,dc.length);
                return unescape(s.substring(0, s.indexOf("; ")));
            }else{
                return null;
            }
        },
        del:function(k){
            var exp = new Date();
            exp.setTime(exp.getTime() - 1);
            var cval=this.get(k);
            if(cval!=null) document.cookie= k + "="+cval+";expires="+exp.toGMTString();
        }
    },
    Trans:{
        ajax: function(url, params, callback, options){
        },
        getText:function(url, params, options){
        },
        getXml:function(url, params, options){
        }
    },
    Position:{
    }
};

//扩展字符串String对象
Ctn.util.extend(String.prototype, {
    left:function(l){
        return this.substr(0, l);
    },
    right:function(l){
        return this.substr(this.length - l, l);
    },
    lTrim:function(v){
        v = v == null ? " \t\r\n" : v;
        var a = v.split("");
        for (var i = 0, l = this.length; i < l; i++)
        {
            if (!a.contains(this.charAt(i))){
                return this.substring(i);
            }
        }
        return "";
    },
    rTrim:function(v){
        v = v == null ? " \t\r\n" : v;
        var a = v.split("");
        for (var i = this.length - 1; i >= 0; i--)
        {
            if (!a.contains(this.charAt(i))){
                return this.substring(0, i + 1);
            }
        }
        return "";
    },
    trim:function(v){
        return this.lTrim(v).rTrim(v);
    },
    toParams:function(){
        var s, a, o = {}, t, n, v, l=0;
        if (this.indexOf('?') > -1){
            s = this.split('?')[1];
        }else{
            s = this;
        }
        a = s.split('&');
        for (var i = 0; i < a.length; i++){
            t = a[i].split('=');
            n = t[0];
            v = t[1];
            if (v == null){
                o[l++] = n;
            }else if(o[n] != null){
                //如果已经是数组
                if (o[n] instanceof Array)
                {
                    o[n].push(v);
                }else{//如果不是数组则改为数组存储
                    t = o[n];
                    o[n] = [];
                    o[n].push(t);
                    o[n].push(v);
                }
            }else{
                o[n] = v;
            }
        }
    },
    //验证
    validate:function(){},
    startsWith:function(v){
        return this.indexOf(v) == 0;
    },
    endsWidth:function(v){
        return this.lastIndexOf(v) == this.length - v.length;
    }
});
//扩展数组Array对象
Ctn.util.extend(Array.prototype, {
    //遍历
    each: function(fn) {
        for (var i = 0, l = this.length; i < l; i++){
            fn(this[i]);
        }
    },
    from: function(v){
        for (var i = 0, l = this.length; i < l; i++){
            this[i] = v[i];
        }
        return this;
    },
    //转换为Int
    toInt : function(){
        for (var i = this.length - 1; i >= 0; i--){
            this[i] = parseInt(this[i]);
        }
        return this;
    },
    //查找
    indexOf:function(v){
        for (var i = 0, l = this.length; i < l; i++)
        {
            if (this[i] == v)
            {
                return i;
            }
        }
        return -1;
    },
    //包含
    contains:function(v){
        if (this.indexOf(v) > -1){
            return true;
        }else{
            return false;
        }
            
    },
    //克隆数组
    clone:function(){
        var v = [];
        for (var i = 0, l = this.length; i < l; i++)
        {
            v.push(this[i]);
        }
        return v;
    },
    //清空
    clear:function(){
        this.length = 0;
        return this;
    },
    //移除
    remove:function(v){
        for (var i = this.length - 1; i >= 0; i--){
            if (this[i] == v){
                this.splice(i, 1);
            }
        }
        return this;
    },
    //移除
    removeAt:function(i){
        var v = this[i];
        this.splice(i, 1);
        return v;
    },
    //插入
    insertAt:function(i, v){
        for (var j = this.length - 1; j >= idx; j--)
        {
            this[j + 1] = this[j];
        }
        this[i] = v;
        return this;
    },
    //压缩
    compact: function() {
        for (var i = this.length - 1; i >= 0; i--)
        {
            if (this[i] == null){
                this.splice(i, 1);
            }
        }
        return this;
    },
    //去除相同项
    uniq: function(){
        for (var i = 0; i < this.length; i++){
            for (var j = this.length - 1; j > i; j--){
                if (this[i] == this[j]){
                    this.splice(j, 1);
                }
            }
        }
        return this;
    }
});
//扩展数字Number对象
Ctn.util.extend(Number.prototype, {});
//扩展Boolean对象
Ctn.util.extend(Boolean.prototype, {
    from: function(v){
        v = typeof(v) == "string" ? v.toLowerCase() : v;
        if (v == false || v == 0 || v == "0" || v == "false"){
            return false;
        }else if(v == true || v == 1 || v == "1" || v == "true"){
            return true;
        }else{
            return this;
        }
    }
});
//扩展Object对象
Ctn.util.extend(Object.prototype, {});
//扩展函数Function对象
Ctn.util.extend(Function.prototype, {
    bind:function(){
        var __method = this, args = new Array().from(arguments), object = args.shift();
        return function() {
            return __method.apply(object, args.concat(new Array().from(arguments)));
        }
    }
});
//扩展日期Date对象
Ctn.util.extend(Date.prototype, {});
//扩展数学Math对象
Ctn.util.extend(Math, {});
//扩展错误Error对象
Ctn.util.extend(Error, {});

})();
